package common.config.exception;

import common.config.http.HttpStatusEnum;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理/error
 *
 * @author 米泽鹏
 * @since 2022-11-30 下午 5:04
 */
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class CustomErrorController extends BasicErrorController {

	public CustomErrorController(ServerProperties serverProperties) {
		super(new DefaultErrorAttributes(), serverProperties.getError());
	}

	/**
	 * 覆盖默认的JSON响应
	 */
	@Override
	public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
		HttpStatusEnum httpStatusEnum = HttpStatusEnum.getStatus(request);
		Map<String, Object> map = new HashMap<>(3);
		map.put("code", httpStatusEnum.getCode());
		map.put("message", httpStatusEnum.getMessage());
		map.put("data", null);
		return new ResponseEntity<>(map, getStatus(request));
	}

}
